package cn.sdstudio.exception;

import cn.sdstudio.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        log.info(request.getHeader("Authorization"));
        log.error("authException:{}",authException);

        response.setContentType("application/json;charset=UTF-8"); // 设置响应类型为 JSON
        response.getWriter().write(
                new ObjectMapper().writeValueAsString(Result.error(401, "未登录或Token无效"))
        );

    }
}
